package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.introspect.TypeResolutionContext;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.utils.StringUtil;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.CourseTeacherDTO;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.CourseTeacherService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author woldier
 * @version 1.0
 * @description 课程发布预览service-impl
 * @date 2023/3/16 18:44
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class CoursePublishServiceImpl implements CoursePublishService {

    private final CourseBaseMapper courseBaseMapper;
    private final CourseBaseInfoService courseBaseInfoService;
    private final CourseMarketMapper courseMarketMapper;
    private final TeachplanService teachplanService;
    private final CourseTeacherService courseTeacherService;
    private final CoursePublishPreMapper coursePublishPreMapper;
    private final CoursePublishMapper coursePublishMapper;
    // 下面的这个问题是启动类放错了位置，放到了和mapper、sercice包一层 出现扫描不到的问题
    // 多模块要注意的东西就是启动类@ComponentScan的注解，看下启动类所在包是不是和所依赖的service接口同一基础包之下，如果不在就加上扫描的service的 基础包
    private final MqMessageService mqMessageService;
    private final MediaServiceClient mediaServiceClient;
    /**
     * @description 获取课程预览所需要的信息
     * @param courseId  课程id
     * @return com.xuecheng.content.model.dto.CoursePreviewDto
     * @author: woldier
     * @date: 2023/3/16 18:45
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) throws XueChengPlusException {
        /*
         * 1.查询课程基本,营销信息
         * 2.查询课程计划信息
         * 3.查询课程教师信息
         */
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        if(courseBaseInfo==null) XueChengPlusException.cast("获取课程基本信息出错");
        List<TeachplanDto> teachplanDtos = teachplanService.findTeachplanTree(courseId);
        if(teachplanDtos==null) XueChengPlusException.cast("获取课程计划信息出错");
        List<CourseTeacher> courseTeachers = courseTeacherService.getIdByCourseTeacherList(courseId);
        if(courseTeachers==null) XueChengPlusException.cast("获取课程老师信息出错");
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanDtos);
        coursePreviewDto.setCourseTeachers(courseTeachers);
        return coursePreviewDto;
    }

    @Override
    @Transactional
    public void commitAudit(Long companyId, Long courseId) throws XueChengPlusException {
        /**
         *
         * 1、查询课程基本信息、课程营销信息、课程计划信息等课程相关信息，整合为课程预发布信息。
         * 2、向课程预发布表course_publish_pre插入一条记录，如果已经存在则更新，审核状态为：已提交。
         * 3、更新课程基本表course_base课程审核状态为：已提交。
         * 约束：
         * 1、对已提交审核的课程不允许提交审核。
         * 2、本机构只允许提交本机构的课程。
         * 3、没有上传图片不允许提交审核。
         * 4、没有添加课程计划不允许提交审核。
         * 5、没有教师不许提交审核
         * */
        CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.getCourseBaseInfo(courseId);
        if (courseBaseInfoDto == null) {
            XueChengPlusException.cast("课程查询不到");
        }
        // 审核状态
        String auditStatus = courseBaseInfoDto.getAuditStatus();
        // 对已提交审核的课程不允许提交审核
        if (auditStatus.equals("202003")) {
            XueChengPlusException.cast("课程已提交，请等待审核");
        }
        Long id = courseBaseInfoDto.getCompanyId();
        // 本机构只允许提交本机构的课程。
        if (!id.equals(companyId)) {
            XueChengPlusException.cast("本机构只允许提交本机构的课程。");
        }
        // 没有上传图片不允许提交审核
        String pic = courseBaseInfoDto.getPic();
        if (StringUtil.isEmpty(pic)) {
            XueChengPlusException.cast("没有上传图片不允许提交审核");
        }
        // 没有添加课程计划不允许提交审核。
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        if (teachplanTree == null || teachplanTree.size()==0) {
            XueChengPlusException.cast("请编写课程计划");
        }
        // 没有教师不许提交审核
        List<CourseTeacher> courseTeachers = courseTeacherService.getIdByCourseTeacherList(courseId);
        if(courseTeachers==null || courseTeachers.size()==0) XueChengPlusException.cast("请填写课程老师信息");
        // 营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        // 转json
        String courseTeachersJson = JSON.toJSONString(courseTeachers);
        String courseMarketJson = JSON.toJSONString(courseMarket);
        String teachplanTreeJson = JSON.toJSONString(teachplanTree);
        // 提交预发布信息
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfoDto,coursePublishPre);
        coursePublishPre.setCompanyId(companyId);
        coursePublishPre.setTeachers(courseTeachersJson);
        coursePublishPre.setMarket(courseMarketJson);
        coursePublishPre.setTeachplan(teachplanTreeJson);
        coursePublishPre.setStatus("202003");
        coursePublishPre.setCreateDate(LocalDateTime.now());
        // 查询预发布表 如果有记录 就更新 没有就插入 主键是课程id
        CoursePublishPre coursePublishPreObj = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreObj == null) {
            // 插入
            coursePublishPreMapper.insert(coursePublishPre);
        } else {
            // 更新
            coursePublishPreMapper.updateById(coursePublishPre);
        }
        // 全量更新 课程基本信息表的审核状态为已提交
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
    }

    /**
     * @description 课程发布
     * @param courseId  课程id
     * @return void
     * @author: woldier
     * @date: 2023/3/26 17:25
     */
    @Override
    @Transactional()
    public void coursePublish(Long companyId,Long courseId) throws XueChengPlusException {
        /**
         * 1. 判断课程预发布表的审核状态,若不为审核通过不允许发布课程
         * 2. 在课程预发布表中status字段指的是课程审核状态,而在课程发布表中的status字段指的是课程的发布状态,因此我们需要修改status字段
         * 3. 设置课程基本信息表的课程发布状态为已发布
         * 4. 将课程发布任务写入的消息表(用于同步redis,elasticsearch,minio)
         */
        // 查询课程预发布信息
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        //判断是否是本机构课程
        if(!coursePublishPre.getCompanyId().equals(companyId))
            XueChengPlusException.cast("只允许提交本机构的课程");
        // 判断审核状态
        if(!coursePublishPre.getStatus().equals("202004"))
            XueChengPlusException.cast("当前课程审核状态不是审核通过,不允许发布");

        // 对象拷贝,设置coursePublish的status字段
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre,coursePublish);
        coursePublish.setStatus("203002");
        // 先查询课程发布表 如果没有在添加 如果存在则更新
        CoursePublish coursePublishObj = coursePublishMapper.selectById(courseId);
        if (coursePublishObj==null){
            //保存课程发布表
            coursePublishMapper.insert(coursePublish);
        }else {
            coursePublishMapper.updateById(coursePublish);
        }

        //更新课程表的状态
        CourseBase courseBase = new CourseBase();
        courseBase.setId(courseId);
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);
        //删除课程预发布表
        coursePublishPreMapper.selectById(courseId);
        //写入事务信息到消息表同步信息
        saveCoursePublishMessage(courseId);
    }

    /**
     * @description TODO 课程发布成功写入消息表
     * @param courseId
     * @return void
     * @author: woldier
     * @date: 2023/3/26 20:15
     */
    @Override
    @Transactional
    public void saveCoursePublishMessage(Long courseId){
        MqMessage mqMessage = mqMessageService.addMessage("course_publish",String.valueOf(courseId),null,null);
        if (mqMessage==null) {
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }

    @Override
    public File generateCourseHtml(Long courseId) {
        //静态化文件
        File htmlFile  = null;
        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/templates").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");
            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");
            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);
            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//            System.out.println(content);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}",e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }
        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String course = mediaServiceClient.uploadFile(multipartFile, "course/"+courseId+".html");
        if(course==null){
            XueChengPlusException.cast("上传静态文件异常");
        }
    }

    @Override
    public CoursePublish getCoursePublish(Long courseId){
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish ;
    }

}
